#include "cdthread.h"
#include<iostream>
using namespace::std;

CDThread::CDThread(){
	running = 0;
}

CDThread::~CDThread(){

}

void CDThread::startcountdown(QTime& c_initTime){
	initTime = c_initTime;
	now = initTime;
	if(running==0){
		running = 1;
		this->start();
	}else{
		running = 0;
		now.setHMS(0,0,0);
		initTime.setHMS(0,0,0);
		emit changeTimer(now);
		this->terminate();
	}
}

void CDThread::pausecountdown(){
	if(running==1){
		running = 0;
		this->terminate();
	}else{
		running = 1;
		this->start();
	}
}

void CDThread::restartcountdown(){
	if(running==0){
		now = initTime;
		emit changeTimer(now);
		running = 1;
		this->start();
	}else{
		now = initTime;
		emit changeTimer(now);
	}
}
void CDThread::run(){

	forever{
		if(running ==0){
			this->terminate();
		}
		this->sleep(1);
		//cerr<<"cdthread running ...";
		QTime temp = countdown();
		//cerr<<"countdown().."<<temp.hour()<<":"<<temp.minute()<<":"<<temp.second()<<"."<<endl;
		emit changeTimer(temp);

	}
}

const QTime& CDThread::countdown(){

	//get current time
	int hour = now.hour();
	int min = now.minute();
	int sec = now.second();
	
	//cerr<<"countdown().."<<hour<<":"<<min<<":"<<sec<<"."<<endl;
	if(sec==0){
		if(min==0){
			if(hour==0){
				//cerr<<"Time is up"<<endl;
				//time is over
				running = 0;
				emit timeUp();
				//this->terminate();
			}else{
				//eg: 01:00:00 => 00:59:59
				now.setHMS(--hour,59,59);
			}	
		}else{
			//eg: 01:21:00 => 01:20:59
			now.setHMS(hour,--min,59);
		}	
	}else{
		now.setHMS(hour,min,--sec);
	}	
	//cerr<<"return qTime.."<<qTime.hour()<<":"<<qTime.minute()<<":"<<qTime.second()<<endl;

	return now;

}
